package com.codefish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codefish.entity.ProvinceCityCounty;
import com.codefish.mapper.ProvinceCityCountyDao;
import com.codefish.service.ProvinceCityCountyService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname ProvinceCityCountyServiceImpl
 * @Description TODO
 * @Date 2021/4/30 22:18
 * @Created 学兔斯基眯眼看世界
 */
@Service
public class ProvinceCityCountyServiceImpl extends ServiceImpl<ProvinceCityCountyDao, ProvinceCityCounty> implements ProvinceCityCountyService {

    /**
     * 省市区树形结构查询
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> queryProvinceCityCounty() {
        // 构建查询条件
        QueryWrapper<ProvinceCityCounty> queryWrapper = new QueryWrapper<ProvinceCityCounty>().eq("status", 1);

        List<ProvinceCityCounty> provinceCityCounties = baseMapper.selectList(queryWrapper);

        return findProvinceCityCountyListByParentId(provinceCityCounties, 0);

    }

    /**
     * 查询全部的省
     *
     * @return
     */
    @Override
    public List<ProvinceCityCounty> queryProvince() {
        // 构建查询条件
        QueryWrapper<ProvinceCityCounty> queryWrapper = new QueryWrapper<ProvinceCityCounty>().eq("status", 1).eq("type", 1);

        List<ProvinceCityCounty> provinceCityCounties = baseMapper.selectList(queryWrapper);
        return provinceCityCounties;
    }

    /**
     * 根据id查询对应下级
     *
     * @param id
     * @return
     */
    @Override
    public List<ProvinceCityCounty> queryCityByProvinceId(Long id) {
        // 构建查询条件
        QueryWrapper<ProvinceCityCounty> queryWrapper = new QueryWrapper<ProvinceCityCounty>().eq("status", 1).eq("pid", id);

        List<ProvinceCityCounty> provinceCityCounties = baseMapper.selectList(queryWrapper);
        return provinceCityCounties;
    }


    private List<Map<String, Object>> findProvinceCityCountyListByParentId(List<ProvinceCityCounty> ProvinceCityCountyList, Integer pid) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (ProvinceCityCounty pcc : ProvinceCityCountyList) {
            if (pcc.getPid().equals(pid)) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", pcc.getName());
                map.put("code", pcc.getCode());
                map.put("children", findProvinceCityCountyListByParentId(ProvinceCityCountyList, pcc.getId()));
                mapList.add(map);
            }
        }
        return mapList;
    }

}
